package com.iwhalecloud.bss.kite.cucc.listener.handler;

import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneAdditionalOfferInstService;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.LabelConsts;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.manager.api.ILocalQuerySceneInstService;
import com.iwhalecloud.bss.kite.dataservice.cache.DcSystemParamCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferDetailCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferRelCache;
import com.iwhalecloud.bss.kite.dataservice.cache.ProdFeeCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.OfferDetail;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.OfferRelInfo;
import com.iwhalecloud.bss.kite.listener.handler.offer.IAdditionnalOfferLinkHandler;
import com.iwhalecloud.bss.kite.listener.handler.offer.helper.AdditionalOfferHelper;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.dto.KiteInstRelDTO;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.enums.RelType;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.service.inf.accept.cache.KiteOrderHandleContextCache;
import com.iwhalecloud.bss.kite.service.scene.bo.OperateSceneAdditionalOfferInstBO;
import com.iwhalecloud.bss.kite.service.scene.req.OperateSceneReqFactory;
import com.iwhalecloud.bss.kite.service.scene.req.impl.AddAdditionalOfferRequest;
import com.ztesoft.bss.base.staticdata.CoreDataOffer;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author liu.zhiyong2
 * @date 2019年6月12日
 * @desc 销售品实例产生的事件：可选包处理器
 */
@Service
public class LocalAdditionalOfferOfOfferHandler implements IAdditionnalOfferLinkHandler {

    @Autowired
    OperateSceneAdditionalOfferInstBO operateSceneAdditionalOfferInstBO;

    @Autowired
    IQuerySceneInstService querySceneInstService;

    @Autowired
    ILocalQuerySceneInstService localQuerySceneInstService;

    @Autowired
    IOperateSceneInstService operateSceneInstService;

    @Autowired
    IOperateSceneAdditionalOfferInstService iOperateSceneAdditionnalOfferInstService;

    @Autowired
    AdditionalOfferHelper additionalOfferHelper;

    @SuppressWarnings("unchecked")
    @Override
    public List<OfferRelInfo> initRestrict(String parentSpecId) {
        List<OfferRelInfo> offerRels = new ArrayList<OfferRelInfo>();

        Offer offer = OfferCache.get(parentSpecId);
        // 默认可选包
        boolean flag = true;
        if (KiteOrderHandleContextCache.getData() != null && KiteOrderHandleContextCache.getData().getPosOrderRequest() != null
            && KeyConsts.ACCEPT_MODE_JK.equals(KiteOrderHandleContextCache.getData().getPosOrderRequest().getAccept_mode())) {
            String askSources = DcSystemParamCache.getDcParamVal("20200915001");
            String askSource = KiteOrderHandleContextCache.getData().getPosOrderRequest().getAsk_source();
            if (askSources.indexOf(askSource) > -1) {
                flag = false;
            }
        }
        if (flag) {
            offerRels.addAll(offer.listDefaultAdditionalOfferRels());
        }
        // 必选可选包
        offerRels.addAll(offer.listMustAdditionalOfferRels());
        List<OfferRelInfo> offerRelInfoList = OfferCache.get(parentSpecId).listAllOfferRels().stream().filter(offerRelInfo -> {
            return CoreDataOffer.OFF_0005_12.equals(offerRelInfo.getzOfferType()) && StringUtils.equalsAny(offerRelInfo.getRelType(), CoreDataOffer.OFF_0006_100000, CoreDataOffer.OFF_0006_120000);
        }).collect(Collectors.toList());
        offerRels.addAll(offerRelInfoList);
        return offerRels;
    }

    @SuppressWarnings("deprecation")
    @Override
    public void  init(String sceneInstId, String parentSpecId, String parentInstId, String custId, String staffId) {

        // 获取约束（必选成员下默认、必选的可选包）
        List<OfferRelInfo> offerRelInfos = this.initRestrict(parentSpecId);
//        Offer mainOffer = OfferCache.get(parentSpecId);
//        List<OfferDetail> offerDetails = mainOffer.listAccessProdDetail();
        //排除自主融合可选包
        //filterAutoMixAdditionalOffer(parentSpecId, offerRelInfos);

//        CustDTO custDTO = ServiceContext.getCust(sceneInstId, custId);

        offerRelInfos.forEach(offerRelInfo -> {
            // 获取可选包成员
            Offer additionaloffer = ProdFeeCache.get(offerRelInfo.getzOfferId());

            List<OfferDetail> additionalOfferDetails = additionaloffer.listAccessProdDetail();

            for (Iterator<OfferDetail> it = additionalOfferDetails.iterator(); it.hasNext();) {
                OfferDetail additionalOfferDetail = it.next();

//                if (!KiteStringUtils.isEmpty(additionalOfferDetail.getMinNum()) && Integer.parseInt(additionalOfferDetail.getMinNum()) <= 0) {
//                    continue;
//                }
//                boolean isRestrictResult = OfferRestrictUtil.isRestrication(additionalOfferDetail.getOfferId(), custDTO.getCustLabelDTO());
//                if (isRestrictResult) {
//                    continue;
//                }

//                offerDetails.forEach(offerDetail -> {
                    this.newAdditionalOffer(sceneInstId, parentInstId, additionaloffer, offerRelInfo, custId, staffId);
//                });



            }
        });
    }


    public void newAdditionalOffer(String sceneInstId, String parentInstId, Offer additionalOffer, OfferRelInfo offerRelInfo, String custId, String staffId) {
//        logger.warn(OfferCache.get(mainOfferDetail.getOfferId()).getOfferName() + "新增可选包" + additionalOffer.getOfferName());
//
//        //1、判断角色和产品Id相同；
//        if (!(KiteStringUtils.equals(mainOfferDetail.getRoleId(), additionalOfferDetail.getRoleId())
//            && KiteStringUtils.equals(mainOfferDetail.getObjId(), additionalOfferDetail.getObjId()))) {
//            return;
//        }
        List<KiteInstRelDTO> offerObjInstRels = querySceneInstService.listInstRelsByAInst(custId, InstType.MAIN_OFFER_INST, parentInstId, InstType.PROD_INST);

        //适用构成约束；
        String rstrOfferProdRelId = offerRelInfo.getRstrOfferProdRelId(); //明细ID
        String rstrOfferProdRoleCd = offerRelInfo.getRstrOfferProdRoleCd(); //角色Id

        if (KiteStringUtils.isNotEmpty(rstrOfferProdRelId) && KiteStringUtils.isNotEmpty(rstrOfferProdRoleCd)) {
            // 适用构成处理
            OfferDetail offerDetail = OfferDetailCache.getOfferDetail(rstrOfferProdRelId);
            KiteInstRelDTO currOfferObjInstRel = null;
            for (KiteInstRelDTO offerObjInstRel : offerObjInstRels) {
                if (StringUtils.equalsAny(offerObjInstRel.getRoleId(), offerDetail.getRoleId(), rstrOfferProdRoleCd)
                    && KiteStringUtils.equals(offerObjInstRel.getzSpecId(), offerDetail.getObjId())) {
                    currOfferObjInstRel = offerObjInstRel;
                    break;
                }
            }

            if (!KiteObjectUtils.isEmpty(currOfferObjInstRel)) {
                operateSceneAdditionalOfferInstBO.initAdditionalOffer(sceneInstId, parentInstId, currOfferObjInstRel,
                    additionalOffer.getOfferId(), custId, staffId);
            }

        }
        else {


            List<KiteOfferInst> additionalOfferInsts = Collections.emptyList();
            KiteOfferInst kiteOfferInst = querySceneInstService.getOfferInst(custId, parentInstId);
            if (Objects.equals(kiteOfferInst.getInstType(), InstType.MAIN_OFFER_INST)) {
                additionalOfferInsts = querySceneInstService.listAdditionalOfferInstsFromMainOfferInst(custId, parentInstId);
            }
            else if (Objects.equals(kiteOfferInst.getInstType(), InstType.MEM_OFFER_INST)) {
                additionalOfferInsts = localQuerySceneInstService.listAdditionalOfferInstsFromMemOfferInst(custId, parentInstId);
            }
            else if (Objects.equals(kiteOfferInst.getInstType(), InstType.PROMOTION_OFFER_INST)) {
                additionalOfferInsts = querySceneInstService.listAdditionalOfferInstsFromPromotionOfferInst(custId, parentInstId);
            }

            //2、判断可选包受理是否存在；
            KiteOfferInst existsAddtionOfferInst = null;
            for (KiteOfferInst additionalOfferInst : additionalOfferInsts) {
                if (Objects.equals(additionalOfferInst.getOfferId(), additionalOffer.getOfferId())) {
                    existsAddtionOfferInst = additionalOfferInst;
                }
            }

            if (Objects.isNull(existsAddtionOfferInst)) {
                KiteOfferInst offerInst = this.querySceneInstService.getOfferInst(sceneInstId, parentInstId);
                KiteInstRelDTO offerObjInstRel = new KiteInstRelDTO();
                offerObjInstRel.setaSpecId(offerInst.getOfferId());
                // 创建可选包品实例
                operateSceneAdditionalOfferInstBO.initAdditionalOffer(sceneInstId, parentInstId, offerObjInstRel, additionalOffer.getOfferId(), custId, staffId);
            }
            else {
                // 如果可选包实例存在，只需要新增明细
                List<OfferDetail> additionalOfferDetails = additionalOffer.listAccessProdDetail();
                for (OfferDetail additionalOfferDetail : additionalOfferDetails) {
                    List<KiteProdInst> prodInsts = querySceneInstService.listProdInstsFromOfferInstByProdId(custId, parentInstId, additionalOfferDetail.getRoleId(), additionalOfferDetail.getObjId());
//                    operateSceneInstService.addInstRel(sceneInstId, InstType.ADDITIONAL_OFFER_INST,
//                        existsAddtionOfferInst.getOfferInstId(), InstType.PROD_INST, prodInsts.get(0).getProdInstId(), RelType.OFFER_OBJ_REL_TYPE_1000, ActionType.A);
                    operateSceneInstService.addOfferObjInstRel(sceneInstId, InstType.ADDITIONAL_OFFER_INST,
                        existsAddtionOfferInst.getOfferInstId(), InstType.PROD_INST, prodInsts.get(0).getProdInstId(), RelType.OFFER_OBJ_REL_TYPE_1000, ActionType.A,
                        additionalOfferDetail.getRoleId(), additionalOfferDetail.getDetailId(), prodInsts.get(0).getOwnerCustId());
                }

            }
        }

    }

    /**
     * 新增成员，获取销售品下的可选包，默认添加构成中有该成员的可选包
     *
     * @param sceneInstId
     * @param parentSpecId
     * @param parentInstId
     * @param custId
     * @param staffId
     * @param roleId
     * @param prodId
     * @param prodInstId
     */
    public void add(String sceneInstId, String parentSpecId, String parentInstId, String custId, String staffId,
        String roleId, String prodId, String prodInstId) {
        // 获取约束 该成员下默认、必选的可选包
        List<OfferRelInfo> offerRelInfos = this.initRestrict(parentSpecId);
        offerRelInfos.forEach(offerRelInfo -> {
            // 获取可选包构成
            Offer additionaloffer = ProdFeeCache.get(offerRelInfo.getzOfferId());

            List<OfferDetail> offerDetails = additionaloffer.listOfferDetails();
            offerDetails.forEach(offerDetail -> {

                boolean isAdd = Boolean.FALSE;
                if (KiteStringUtils.equals(offerDetail.getRoleId(), roleId)) {
                    isAdd = Boolean.TRUE;
                }
                //判断适用构成
                if (KiteStringUtils.equals(offerRelInfo.getRstrOfferProdRoleCd(), roleId)) {
                    isAdd = Boolean.TRUE;
                }

                //判断明细是否存在；3408219672346096
                List<KiteInstRelDTO> offObjInstRels = querySceneInstService.listInstRelsByZInst(custId, InstType.PROD_INST, prodInstId, InstType.ADDITIONAL_OFFER_INST);
                if (isAdd && KiteStringUtils.equals(offerDetail.getObjId(), prodId) && Objects.equals(offObjInstRels.size(), 0)) {
                    AddAdditionalOfferRequest request = OperateSceneReqFactory.createAddAddtionalOfferRequest(sceneInstId, parentInstId, prodInstId, additionaloffer.getOfferId(), custId, staffId);
                    operateSceneAdditionalOfferInstBO.addAdditionalOffer(request);
                }
            });
        });

    }

    @Override
    public boolean check(String sceneInstId, String specId, String instId) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void apply() {
        /*
         * if (!this.check()) { return; }
         */

    }

    @Override
    public void remove(String sceneInstId, String custId, String specId, String instId) {
        // 是否必选可选包
        KiteOfferInst mainOfferInst = querySceneInstService.getMainOfferInstByAdditionalOfferInstId(sceneInstId,
            instId);
        KiteOfferInst additionalOfferInst = querySceneInstService.getOfferInst(custId, instId);
        Offer mainOffer = OfferCache.get(mainOfferInst.getOfferId());
        List<Offer> offerList = mainOffer.listMustAdditionalOffers(mainOffer.getOfferId());
        for (Offer offer : offerList) {
            if (offer.getOfferId().equals(additionalOfferInst.getOfferId())) {
                ErrorConsts.ADDITIONAL_OFFER_OF_PROD_REMOVE_ERR.throwOut(additionalOfferInst.getOfferName());
                return;
            }
        }
        // operateSceneAdditionalOfferInstBO.removeAdditionalOffer(sceneInstId, additionalOfferInst.getOfferId(),
        // instId, "", ""); //TODO 新增custId、staffId 待补充
    }

    @Override
    public void load(String sceneInstId, String specId, String instId, String custId, String staffId) {
        // TODO Auto-generated method stub

    }

    /**
     * 过滤掉自主融合可选包
     * @param parentSpecId
     * @param offerRelInfos
     */
    public void filterAutoMixAdditionalOffer(String parentSpecId, List<OfferRelInfo> offerRelInfos) {
        if (offerRelInfos == null) {
            return;
        }

        List<OfferRelInfo> offerRelInfoList = OfferRelCache.listAdditionalOffersByLabel(parentSpecId, LabelConsts.LABLE_ID_9000, KeyConsts.OFFER_TYPE_12);
        Set<String> autoMixAdditionalOfferList = offerRelInfoList.stream().map(t -> String.valueOf(t.getzOfferId())).collect(Collectors.toSet());

        if (CollectionUtils.isNotEmpty(autoMixAdditionalOfferList)) {
            offerRelInfos.removeIf(
                offerRelInfo -> autoMixAdditionalOfferList.contains(offerRelInfo.getzOfferId()));
        }
    }
}
